Creating, Running, and Understanding a Basic Flutter Application
A Flutter application is built using the Dart programming language and Flutter's widget-based UI framework. A Flutter project contains source code, configuration files, platform-specific folders, assets, dependencies, and test files.
In this lesson, you will learn how to create a Flutter application, understand its basic project structure, write your first Flutter UI, run the application on a device or browser, understand the widget tree, and use hot reload during development.
For additional Flutter learning and course information, visit
JustAcademy Flutter Training
and
Register for a Course Demo.
1. What is a Flutter Application?
A Flutter application is a cross-platform application created using Flutter and Dart. The same Flutter project can be used to build applications for platforms such as Android, iOS, web, Windows, macOS, and Linux, depending on the project's configured targets.
Flutter applications are primarily composed of widgets. Text, buttons, layouts, screens, navigation elements, images, forms, and many other UI elements are represented using widgets.
Basic Flutter Application Flow
- Create a Flutter project.
- Open the project in an IDE such as VS Code or Android Studio.
- Write application code inside the
lib directory.
- Start the application on an available device.
- Modify the Dart code.
- Use hot reload to quickly see UI changes.
- Debug and test the application.
2. Prerequisites
Before creating and running a Flutter application, make sure Flutter is installed and configured correctly.
- Flutter SDK
- Dart SDK, which is included with Flutter
- VS Code, Android Studio, or another supported IDE
- Flutter and Dart extensions/plugins
- An Android emulator, iOS simulator, physical device, desktop target, or supported web browser
- Required platform SDKs for the platform you want to run
Check Flutter Installation
flutter doctor
The flutter doctor command checks the development environment and reports configuration or installation issues.
Check Flutter Version
flutter --version
3. Creating a New Flutter Application
A Flutter application can be created from an IDE or directly from the terminal using the Flutter CLI. The Flutter CLI uses flutter create to generate a new project structure and starter files.
Using the Terminal
Open a terminal and navigate to the directory where you want to create the project.
flutter create my_first_app
Then move into the project directory:
cd my_first_app
Run the application:
flutter run
Flutter creates the project folder, generates the initial files, and retrieves the required dependencies. Flutter project names conventionally use lowercase letters with underscores, such as my_first_app.
Creating a Minimal Project
You can also create a project with a minimal starting Dart file using the --empty option.
flutter create --empty my_first_app
This is useful when you want to start with a smaller amount of generated application code.
4. Creating a Flutter Application Using VS Code
- Open VS Code.
- Open the Command Palette using
Ctrl + Shift + P on Windows/Linux or Cmd + Shift + P on macOS.
- Search for
Flutter: New Project.
- Select the Flutter application template.
- Select the parent directory where the project should be created.
- Enter a project name such as
my_first_app.
- Wait for Flutter to initialize the project.
- Open
lib/main.dart.
Flutter's official setup documentation describes creating an application from VS Code using the Flutter extension and then running it on a selected device.
5. Understanding the Flutter Project Structure
A newly generated Flutter project contains several important files and directories.
my_first_app/
│
├── android/
├── ios/
├── lib/
│ └── main.dart
├── test/
├── web/
├── windows/
├── macos/
├── linux/
├── pubspec.yaml
├── pubspec.lock
├── README.md
└── .gitignore
Important Project Components
File/Folder |
Purpose |
|---|
lib/ |
Contains the main Dart source code of the application. |
lib/main.dart |
Common entry point for a Flutter application. |
android/ |
Android-specific project files. |
ios/ |
iOS-specific project files. |
web/ |
Web-specific project files. |
test/ |
Application test files. |
pubspec.yaml |
Project metadata, dependencies, assets, fonts, and Flutter configuration. |
pubspec.lock |
Records resolved package versions for the project. |
.gitignore |
Specifies files and folders that should not normally be committed to Git. |
README.md |
Project documentation. |
6. Understanding main.dart
The main.dart file commonly contains the starting point of a Flutter application. Dart programs begin execution from the main() function.
Basic Example
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: Scaffold(
body: Center(
child: Text('Hello Flutter!'),
),
),
),
);
}
Explanation
import 'package:flutter/material.dart'; imports Flutter's Material Design widgets.
void main() is the Dart entry-point function.
runApp() starts the Flutter application with the supplied root widget.
MaterialApp provides application-level Material Design functionality.
Scaffold provides a basic visual screen structure.
Center centers its child.
Text displays text on the screen.
7. Understanding runApp()
The runApp() function takes a widget and makes it the root of the application's widget tree.
void main() {
runApp(
const Text('Hello Flutter'),
);
}
In a practical application, the root is usually a widget such as MaterialApp or CupertinoApp.
void main() {
runApp(
const MaterialApp(
home: HomePage(),
),
);
}
The widget passed to runApp() becomes the starting point from which Flutter builds the rest of the widget tree.
8. Understanding the Widget Tree
Flutter builds user interfaces using a hierarchical structure called the widget tree. A widget can contain other widgets, creating parent-child relationships.
For example:
MaterialApp
│
└── Scaffold
│
├── AppBar
│ └── Text
│
└── Center
└── Text
This means that the application is constructed by composing smaller widgets into larger widgets.
Example Widget Tree in Code
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('My App'),
),
body: const Center(
child: Text('Welcome'),
),
),
)
Here, MaterialApp is the top-level widget. It contains a Scaffold, which contains an AppBar and a body. The body contains a Center, which contains a Text widget.
9. Creating a Basic Flutter Screen
Let's create a simple application that displays a welcome message.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My First Flutter App',
home: Scaffold(
appBar: AppBar(
title: const Text('My First Flutter App'),
),
body: const Center(
child: Text(
'Welcome to Flutter!',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
),
);
}
}
What Happens in This Program?
- Dart starts execution from
main().
runApp() receives the MyApp widget.
MyApp extends StatelessWidget.
- The
build() method describes the UI.
MaterialApp configures the application.
Scaffold creates the basic page structure.
AppBar displays the application bar.
Center places its child in the center.
Text displays the welcome message.
10. StatelessWidget
A StatelessWidget is generally used when the widget's UI does not manage mutable state internally.
Example
class WelcomeMessage extends StatelessWidget {
const WelcomeMessage({super.key});
@override
Widget build(BuildContext context) {
return const Text(
'Welcome to Flutter!',
);
}
}
The widget can be reused in another part of the application.
Scaffold(
body: Center(
child: WelcomeMessage(),
),
)
11. StatefulWidget
A StatefulWidget is useful when the UI needs to change because of mutable state, such as a counter value, checkbox state, form input, or selected item.
Basic Example
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int count = 0;
void increaseCount() {
setState(() {
count++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Counter'),
),
body: Center(
child: Text(
'Count: $count',
style: const TextStyle(fontSize: 28),
),
),
floatingActionButton: FloatingActionButton(
onPressed: increaseCount,
child: const Icon(Icons.add),
),
);
}
}
Why is setState() Used?
When a state value changes, setState() tells Flutter that the widget's state has changed and that the affected UI should be rebuilt.
12. Running the Flutter Application
After creating a Flutter application, you need a target device. This can be a physical device, emulator, simulator, browser, or another supported target.
Check Available Devices
flutter devices
This command lists devices that Flutter can detect and use for running the application.
Run the Application
flutter run
Flutter will build the application and allow you to select or use an available target.
Run on Chrome
flutter run -d chrome
This is useful when you want to test a Flutter application as a web application in Chrome.
Run on a Specific Device
flutter run -d <device-id>
For example:
flutter run -d chrome
13. Running the App from VS Code
- Open the Flutter project in VS Code.
- Make sure a device is selected.
- Open
lib/main.dart.
- Click the Run/Debug option.
- Alternatively, press
F5 to start debugging.
The Flutter extension provides tools for selecting devices, running applications, debugging, inspecting widgets, and accessing Flutter development tools.
14. Running the App from Android Studio
- Open Android Studio.
- Open your Flutter project.
- Wait for project indexing and dependency processing to complete.
- Start an Android emulator or connect a physical Android device.
- Select the target device.
- Open
lib/main.dart.
- Click the Run button.
The application will be built and launched on the selected device.
15. Understanding Hot Reload
One of Flutter's important development features is hot reload. It allows developers to modify Dart code and quickly see the result in the running application while preserving the current application state in supported situations.
Example
Suppose your application contains:
Text('Hello Flutter')
Change it to:
Text('Welcome to Flutter Development')
After saving the code or triggering hot reload, the running application can update to display the new text without requiring a complete application restart.
Terminal Hot Reload
When the application is running through flutter run, press:
r
This triggers hot reload in the running debug session.
16. Hot Reload vs Hot Restart vs Full Restart
Feature |
Description |
|---|
Hot Reload |
Loads updated source code and rebuilds the widget tree while generally preserving the current state. |
Hot Restart |
Restarts the Flutter application and resets application state. |
Full Restart |
Stops and starts the application again and can require more extensive rebuilding/recompilation. |
Hot reload is particularly useful when working on UI layouts, styling, widget composition, and many other development tasks.
17. Understanding pubspec.yaml
Every Flutter project contains a pubspec.yaml file. It contains project metadata and configuration such as dependencies, assets, fonts, and Flutter-specific options.
Example
name: my_first_app
description: A basic Flutter application.
environment:
sdk: ^3.0.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
The exact generated contents and SDK constraints can vary according to the Flutter/Dart version and project configuration.
Adding a Package
flutter pub add http
Flutter updates the project's dependency configuration and resolves the package.
18. Understanding pubspec.lock
The pubspec.lock file records resolved versions of dependencies for the project. This helps maintain consistent dependency resolution when the project is built again.
You generally should not manually edit this file unless you understand the dependency-management implications.
19. Building a More Practical Basic Application
The following example creates a simple profile-style screen with an application bar, profile icon, name, description, and button.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Student Profile',
home: Scaffold(
appBar: AppBar(
title: const Text('Student Profile'),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircleAvatar(
radius: 50,
child: Icon(
Icons.person,
size: 50,
),
),
const SizedBox(height: 20),
const Text(
'Manish',
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
const Text(
'Flutter Developer',
style: TextStyle(fontSize: 18),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {},
child: const Text('View Profile'),
),
],
),
),
),
),
);
}
}
Widgets Used
Widget |
Purpose |
|---|
MaterialApp |
Provides the application's Material Design environment. |
Scaffold |
Provides the basic page structure. |
AppBar |
Displays the top application bar. |
Center |
Centers its child. |
Padding |
Adds space around its child. |
Column |
Arranges children vertically. |
CircleAvatar |
Displays a circular avatar or profile area. |
Text |
Displays text. |
SizedBox |
Creates fixed spacing. |
ElevatedButton |
Creates a Material button. |
20. Understanding Parent and Child Widgets
Flutter layouts are created by placing widgets inside other widgets. The widget containing another widget is called the parent, while the contained widget is its child.
Example
Center(
child: Text('Hello'),
)
Here:
Center is the parent widget.
Text is the child widget.
Multiple Children
Some widgets support multiple children, such as Column and Row.
Column(
children: [
Text('Name'),
Text('Email'),
ElevatedButton(
onPressed: () {},
child: Text('Submit'),
),
],
)
21. Row and Column
Column
A Column arranges its children vertically.
Column(
children: [
Text('First'),
Text('Second'),
Text('Third'),
],
)
Row
A Row arranges its children horizontally.
Row(
children: [
Icon(Icons.home),
SizedBox(width: 10),
Text('Home'),
],
)
22. Understanding BuildContext
The BuildContext represents the location of a widget within the widget tree. It is commonly used to access information about the widget's position in the tree and to interact with inherited widgets or navigation and theme functionality.
Example
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(
'Hello Flutter',
),
),
);
}
The context parameter is automatically provided to the build() method.
23. Debugging a Basic Flutter Application
When an application does not behave as expected, Flutter provides several debugging tools. Commonly used tools include the debugger, Flutter Inspector, DevTools, console output, breakpoints, and error messages.
Using print()
void main() {
print('Application started');
runApp(const MyApp());
}
Output can be viewed in the IDE's debug console or terminal, depending on how the application is launched.
Flutter Inspector
The Flutter Inspector helps developers inspect the widget tree and understand widget properties and layout. It is useful for finding layout problems and understanding how widgets are arranged.
24. Common Flutter Errors
Error 1: No Device Available
Check available devices:
flutter devices
Then start an emulator or connect a supported physical device.
Error 2: Flutter Command Not Found
This commonly indicates that the Flutter SDK is not correctly available through the system PATH or the terminal session needs to be restarted after configuration.
Verify the installation with:
flutter doctor
Error 3: Dependency Problem
Try:
flutter pub get
Error 4: Application Does Not Reflect a Change
Make sure the application is running in debug mode and trigger hot reload. If necessary, use hot restart or stop and start the application again.
25. Useful Flutter Commands
Command |
Purpose |
|---|
flutter doctor |
Checks the Flutter development environment. |
flutter --version |
Displays Flutter version information. |
flutter create my_app |
Creates a new Flutter project. |
flutter create --empty my_app |
Creates a Flutter project with a minimal starting application. |
flutter devices |
Lists available devices. |
flutter run |
Builds and runs the application. |
flutter run -d chrome |
Runs the application in Chrome. |
flutter pub get |
Gets project dependencies. |
flutter pub add package_name |
Adds a package dependency. |
flutter clean |
Removes generated build artifacts and can help resolve certain build issues. |
26. Complete Step-by-Step Workflow
- Install Flutter SDK.
- Configure your IDE.
- Run
flutter doctor.
- Create a new project using
flutter create my_first_app.
- Open the project in VS Code or Android Studio.
- Open
lib/main.dart.
- Understand the
main() function.
- Understand
runApp().
- Create a root widget.
- Use
MaterialApp for a Material Design application.
- Use
Scaffold to create the basic screen structure.
- Add widgets such as
Text, Column, Row, and buttons.
- Run
flutter devices to check available targets.
- Run the application using
flutter run.
- Make a change in
main.dart.
- Use hot reload to see the change.
- Use Flutter Inspector and DevTools for debugging.
- Organize the application into reusable widgets as the project grows.
27. Mini Practical Project: Greeting App
Build a simple greeting application as a beginner exercise.
import 'package:flutter/material.dart';
void main() {
runApp(const GreetingApp());
}
class GreetingApp extends StatelessWidget {
const GreetingApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Greeting App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.waving_hand,
size: 70,
),
const SizedBox(height: 20),
const Text(
'Hello, Flutter!',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
const Text(
'Welcome to Flutter development.',
style: TextStyle(fontSize: 18),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
print('Button clicked');
},
child: const Text('Get Started'),
),
],
),
),
),
);
}
}
Learning Objectives from This Example
- Creating a Flutter application.
- Using
main().
- Using
runApp().
- Creating a
StatelessWidget.
- Using
MaterialApp.
- Using
Scaffold.
- Using
AppBar.
- Using
Column.
- Using
Text.
- Using
Icon.
- Using
ElevatedButton.
- Handling a button callback.
28. Basic Application Architecture
For a small application, keeping code in main.dart can be convenient. As an application grows, separating screens, widgets, models, services, and other responsibilities into different files and directories makes the project easier to maintain.
Example Structure
lib/
├── main.dart
├── screens/
│ └── home_screen.dart
├── widgets/
│ └── custom_button.dart
├── models/
│ └── user.dart
└── services/
└── api_service.dart
A common architectural principle is separation of concerns: different parts of the application should have clearly defined responsibilities. Flutter's architecture guidance describes separating UI and data responsibilities as a foundation for scalable applications.
29. Beginner Practice Tasks
- Create a project named
student_app.
- Change the application title.
- Change the AppBar title.
- Display your name using a
Text widget.
- Add an
Icon.
- Add a profile-style
CircleAvatar.
- Add an
ElevatedButton.
- Print a message when the button is clicked.
- Change the text and test hot reload.
- Run the application on Chrome.
- Run the application on an Android emulator.
- Inspect the widget tree using Flutter Inspector.
30. Interview Questions
Q1. What is Flutter?
Flutter is a UI framework and development toolkit used to build applications using Dart and a widget-based approach.
Q2. What is main()?
main() is the entry point of a Dart application.
Q3. What is runApp()?
runApp() takes a widget and makes it the root of the Flutter widget tree.
Q4. What is a widget tree?
A widget tree is the hierarchical structure created by composing Flutter widgets and their child widgets.
Q5. What is MaterialApp?
MaterialApp provides application-level functionality and Material Design behavior for Flutter applications.
Q6. What is Scaffold?
Scaffold provides a basic visual structure for a Material Design screen, such as an AppBar, body, floating action button, drawer, and related areas.
Q7. What is hot reload?
Hot reload injects updated Dart code into a running debug application and rebuilds the widget tree while generally preserving the current state.
Q8. What is the difference between StatelessWidget and StatefulWidget?
A StatelessWidget is generally used when the widget does not manage mutable state internally, while a StatefulWidget is used when its UI needs to respond to mutable state changes.
Q9. What is pubspec.yaml?
It is the project's configuration file containing metadata, dependencies, assets, fonts, and Flutter-specific configuration.
Q10. How do you run a Flutter application from the terminal?
flutter run
31. Quick Revision
- Flutter applications are written using Dart.
- Flutter UIs are built from widgets.
main() is the Dart entry point.
runApp() starts the Flutter UI with a root widget.
- The root widget forms the beginning of the widget tree.
MaterialApp is commonly used for Material Design applications.
Scaffold provides a basic Material screen structure.
StatelessWidget is used for widgets that do not manage mutable state internally.
StatefulWidget is used when UI needs to respond to mutable state.
pubspec.yaml manages project metadata and dependencies.
flutter create creates a new Flutter project.
flutter run runs the application.
flutter devices lists available devices.
flutter doctor checks the development environment.
- Hot reload speeds up the development cycle.
- Flutter Inspector helps inspect the widget tree and layout.
32. Useful Learning Resources
For structured Flutter learning, course information, and practical training, visit:
33. Conclusion
Creating and running a basic Flutter application is the foundation for Flutter development. The typical workflow begins with creating a project using flutter create, understanding the generated project structure, opening lib/main.dart, creating widgets, starting the application with runApp(), and running it on a suitable device.
The most important concepts for beginners are Dart's main function, runApp(), widgets, widget trees, MaterialApp, Scaffold, StatelessWidget, StatefulWidget, pubspec.yaml, flutter run, and hot reload. Once these concepts are understood, developers can gradually move toward navigation, forms, APIs, state management, animations, local storage, authentication, and complete production applications.